<template>
  <el-select
    v-model="nv[fvData.fdName]"
    placeholder="Select"
    size="large"
    clearable
    :multiple="multiple"
    style="width: 240px"
    v-if="nv"
  >
    <el-option
      v-for="item in options"
      :key="item[expression.sourceFdName]"
      :label="item[expression.sourceFdName]"
      :value="item[expression.sourceFdName]"
    />
  </el-select>
</template>

<script>
import { onMounted, ref, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
export default {
  name: 'DataSourceSelect',
  props: {
    fvData: {
      default: null,
      type: Object
    }
  },
  setup (props) {
    const nv = computed(() => {
      return props.fvData.getNv();
    });
    const expression = ref({});
    const multiple = ref(false)
    const currentInstance = getCurrentInstance();

    function getParentNvLayout() {
      let parent = currentInstance.parent;
      while (parent != null) {
        if (parent.type.name === "NvLayout") { break; }
        parent = parent.parent;
      }
      return parent.proxy;
    }

    const options = computed(() => {
      const nvLayout = getParentNvLayout();
      const dataSource = nvLayout.getDataSource(expression.value.sourceName);
      if (dataSource == null) { return []; }
      const sourceNv = dataSource.getNv();
      if (sourceNv == null) { return [] };
      const childNvs = sourceNv[expression.value.childNdName];
      return childNvs;
    });

    onMounted(() => {
      const str = props.fvData.fdLayout.expression;
      if (!str) {
        ElMessage({
          type: 'error',
          message: '没有配置自动改填充组件表达式'
        });
        return;
      }
      expression.value = JSON.parse(str);
    });

    return {
      nv,
      expression,
      options,
      multiple
    }
  }
}
</script>
